package tt.dz.egobus.api.common;

import tt.dz.egobus.api.RequestParameter;
import tt.dz.egobus.api.exception.ResponseException;
import tt.dz.egobus.base.context.SpringApplicationHolder;
import tt.dz.egobus.bean.CodeStatus;
import tt.dz.egobus.bean.I18NCode;
import tt.dz.egobus.i18n.I18NProperties;
import tt.dz.egobus.i18n.SingletonI18NProperties;
import tt.dz.egobus.servicemanager.bean.SpringConfigConstant;

import java.util.HashMap;
import java.util.Map;

import static tt.dz.egobus.bean.I18NCodeEnum.RPC_PARAM_ILLEGAL_ERROR;

/**
 * @author Anson
 * @date 17-3-15
 * @name 公共api的公共方法
 * @since 1.0.1
 */
public abstract class CommonApiService {

    protected static final I18NProperties I18N_PROPERTIES = SingletonI18NProperties.SINGL_TON.properties();


    protected Map<String, Object> cacheService = new HashMap<String, Object>();

    public SpringConfigConstant getSpringConfigConstant() {
        return this.getService("springConfigConstant", SpringConfigConstant.class);
    }

    /**
     * @param name
     * @param clazz
     * @author Anson
     * @date 17-3-15
     * @name 获取Spring托管的服务
     * @since 1.0.1
     */
    @SuppressWarnings("unchecked")
    protected <T> T getService(String name, Class<T> clazz) {
        Object o = this.cacheService.get(name);
        T t = null;
        if (o == null) {
            t = SpringApplicationHolder.getBean(name, clazz);
            this.cacheService.put(name, t);
        } else {
            t = (T) o;
        }
        return t;
    }

    /**
     * @param name
     * @param clazz
     * @author Anson
     * @date 17-3-15
     * @name 重新获取Spring托管的服务, 一些服务需要不是单例服务对象，需要调用这个方法获取
     * @since 1.0.1
     */
    @SuppressWarnings("unchecked")
    protected <T> T getNewService(String name, Class<T> clazz) {
        return SpringApplicationHolder.getBean(name, clazz);
    }

    /**
     * 获取资源配置信息
     *
     * @param code
     * @return
     */
    protected CodeStatus get(I18NCode code) {
        return I18N_PROPERTIES.get(String.valueOf(code.getCode()));
    }

    /**
     * @param requestParameter
     * @author Anson
     * @date 17-3-29
     * @name 请求参数进行前置校验
     * @since 1.0.3
     */
    protected void validateRequest(RequestParameter requestParameter) throws ResponseException {
        if (requestParameter == null || !requestParameter.validate()) {
            throw new ResponseException(RPC_PARAM_ILLEGAL_ERROR);
        }
    }
}
